import React, { useState, useEffect, useRef } from 'react';

import { getArticlesAPI, delArticleByIdAPI } from 'api/articles';
import {
  Card,
  Breadcrumb,
  Radio,
  Button,
  Form,
  DatePicker,
  Table,
  Tag,
  Space,
  message,
  Modal,
} from 'antd';

import { EditOutlined, DeleteOutlined } from '@ant-design/icons';

import { Link } from 'react-router-dom';

import defaultImg from 'assets/error.png';
import Channel from 'components/Channel';

export default function ArticleList(props) {
  const formDataRef = useRef();
  const pageInfoRef = useRef({});
  const onFinish = (values) => {
    // console.log(values);
    let formData = { ...values };

    if (formData.status === -1) {
      delete formData.status;
      console.log(formData);
    }

    if (formData.data) {
      const begin_pubdate = formData.data[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      const end_pubdate = formData.data[0]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      formData.begin_pubdate = begin_pubdate;
      formData.end_pubdate = end_pubdate;
      delete formData.data;
    }
    formDataRef.current = formData;
    getArticleList(formData);
  };
  // 获取频道列表
  // const [channels, setchannles] = useState([]);
  // const loadChannels = async () => {
  //   const res = await loadChannelAPI();
  //   setchannles(res.data.channels);
  // };

  // 获取文章列表
  const [article, setArticle] = useState({});
  const getArticleList = async (params) => {
    const res = await getArticlesAPI(params);
    setArticle(res.data);
  };
  useEffect(() => {
    // loadChannels();
    getArticleList();
  }, []);
  const delArtileById = (id) => {
    // 1. 使用Modal框，提示用户确认
    Modal.confirm({
      title: '温馨提示',
      content: '你确定要删除这篇文章？',
      // 2. onOk表示点击确定时触发， 💥注意async的位置
      onOk: async () => {
        await delArticleByIdAPI(id);
        message.success('删除成功', 1);
        const formData = formDataRef.current || {};
        getArticleList({ ...formData, ...pageInfoRef.current });
      },
    });
  };
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        return (
          <img
            src={cover.images[0] || defaultImg}
            alt=""
            style={{ width: 100, height: 60, objectFit: 'cover' }}
          />
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      onCell: () => {
        return {
          style: {
            maxWidth: 150,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => {
        const obj = articleStatus.find((v) => v.id === status);
        return <Tag color={obj.color}>{obj.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'active',
      render: (value, record) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => props.history.push(`/edit/${record.id}`)}
            />
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => delArtileById(record.id)}
            />
          </Space>
        );
      },
    },
  ];
  const pageChange = (page, per_page) => {
    pageInfoRef.current = { page, per_page };
    const formData = formDataRef.current || {};
    getArticleList({ page, per_page, ...formData });
  };
  return (
    <div style={{ paddingTop: 22 }}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
      >
        <Form
          onFinish={onFinish}
          autoComplete="off"
          initialValues={{ status: -1 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          {/* <Form.Item label="频道" name="channel_id">
            <Select style={{ width: 200 }} placeholder="请选择频道列表">
              {channels.map((item) => {
                return (
                  <Select.Option key={item.id} value={item.id}>
                    {item.name}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item> */}
          {/* 组件导入 */}
          <Form.Item label="频道" name="channel_id">
            <Channel></Channel>
          </Form.Item>
          <Form.Item label="日期" name="data">
            <DatePicker.RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        <p>根据筛选条件共查询到 {article.total_count} 条结果：</p>
        <Table
          rowKey="id"
          dataSource={article.results}
          columns={columns} // 分页器配置
          pagination={{
            // 控制位置
            position: ['bottomCenter'],
            // 控制总条数
            total: article.total_count,
            // 当页码或页容量改变时触发回调函数
            onChange: pageChange,
            pageSize: article.perPage,
            current: article.page,
          }}
        />
      </Card>
    </div>
  );
}
